package com.yanfan.zutai.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yanfan.common.config.RuoYiConfig;
import com.yanfan.common.utils.DateUtils;
import com.yanfan.common.utils.SecurityUtils;
import com.yanfan.zutai.domain.BDeviceZt;
import com.yanfan.zutai.domain.SysUpload;
import com.yanfan.zutai.mapper.BDeviceZtMapper;
import com.yanfan.zutai.service.IBDeviceZtService;
import com.yanfan.zutai.service.ISysUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 云组态Service业务层处理
 *
 * @author ruoyi
 * @date 2022-05-21
 */
@Service
public class BDeviceZtServiceImpl implements IBDeviceZtService {
    @Autowired
    private BDeviceZtMapper bDeviceZtMapper;
    @Autowired
    private ISysUploadService sysUploadService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 打包部署dist的路径
     */
    @Value("${packPath:/var/data/nginx/html/vue}")
    private String packPath;

    private static void compressFolder(String sourceFolder, String folderName, ZipOutputStream zipOutputStream) throws IOException {
        File folder = new File(sourceFolder);
        File[] files = folder.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    // 压缩子文件夹
                    compressFolder(file.getAbsolutePath(), folderName + "/" + file.getName(), zipOutputStream);
                } else {
                    // 压缩文件
                    addToZipFile(folderName + "/" + file.getName(), file.getAbsolutePath(), zipOutputStream);
                }
            }
        }
    }

    private static void addToZipFile(String fileName, String fileAbsolutePath, ZipOutputStream zipOutputStream) throws IOException {
        // 创建ZipEntry对象并设置文件名
        ZipEntry entry = new ZipEntry(fileName);
        zipOutputStream.putNextEntry(entry);

        // 读取文件内容并写入Zip文件
        try (FileInputStream fileInputStream = new FileInputStream(fileAbsolutePath)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                zipOutputStream.write(buffer, 0, bytesRead);
            }
        }

        // 完成当前文件的压缩
        zipOutputStream.closeEntry();
    }

    /**
     * 查询云组态
     *
     * @param id 云组态ID
     * @return 云组态
     */
    @Override
    public BDeviceZt selectBDeviceZtById(Long id) {
        return bDeviceZtMapper.selectBDeviceZtById(id);
    }

    /**
     * 查询云组态列表
     *
     * @param bDeviceZt 云组态
     * @return 云组态
     */
    @Override
    public List<BDeviceZt> selectBDeviceZtList(BDeviceZt bDeviceZt) {
        return bDeviceZtMapper.selectBDeviceZtList(bDeviceZt);
    }

    /**
     * 新增云组态
     *
     * @param bDeviceZt 云组态
     * @return 结果
     */
    @Override
    public int insertBDeviceZt(BDeviceZt bDeviceZt) {
        bDeviceZt.setCreateTime(DateUtils.getNowDate());
        Snowflake snowflake = IdUtil.getSnowflake(6, 2);
        long id = snowflake.nextId();
        bDeviceZt.setId(id);
        return bDeviceZtMapper.insertBDeviceZt(bDeviceZt);
    }

    /**
     * 修改云组态
     *
     * @param bDeviceZt 云组态
     * @return 结果
     */
    @Override
    public int updateBDeviceZt(BDeviceZt bDeviceZt) {
        bDeviceZt.setUpdateTime(DateUtils.getNowDate());
        return bDeviceZtMapper.updateBDeviceZt(bDeviceZt);
    }

    /**
     * 批量删除云组态
     *
     * @param ids 需要删除的云组态ID
     * @return 结果
     */
    @Override
    public int deleteBDeviceZtByIds(Long[] ids) {
        return bDeviceZtMapper.deleteBDeviceZtByIds(ids);
    }

    /**
     * 删除云组态信息
     *
     * @param id 云组态ID
     * @return 结果
     */
    @Override
    public int deleteBDeviceZtById(Long id) {
        return bDeviceZtMapper.deleteBDeviceZtById(id);
    }

    @Override
    public String download(BDeviceZt bDeviceZt) {
        FileOutputStream fileOutputStream = null;
        ZipOutputStream zipOutputStream = null;
        String fileName = "dist_" + IdUtil.simpleUUID() + ".zip";
        try {
            String packPathJson = packPath + "/spa/config.js";
            File packFilePath = new File(packPathJson);
            if (!packFilePath.exists()) {
                packFilePath.createNewFile();
            }
            fileOutputStream = new FileOutputStream(packPathJson);
            // 填充数据到JSON对象
            BeanPropertyRowMapper<BDeviceZt> bDeviceDetailMapper = new BeanPropertyRowMapper<>(BDeviceZt.class);
            String sql = "select device_mac,guid,device_zt_data from b_device_zt where id=?";
            bDeviceZt = jdbcTemplate.queryForObject(sql, bDeviceDetailMapper, bDeviceZt.getId());
            String jsonString = bDeviceZt.getDeviceZtData();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("baseURL", "http://81.68.197.219:10071/prod-api/");
            jsonObject.put("webTopoData", jsonString);
            String configJs = "window.PLATFROM_CONFIG = " + JSON.toJSONString(jsonObject);
            fileOutputStream.write(configJs.getBytes(StandardCharsets.UTF_8));
            String folderName = "";// 为空是压缩的文件夹不追加目录
            File downFilePath = new File(RuoYiConfig.getDownloadPath());
            if (!downFilePath.exists()) {
                downFilePath.createNewFile();
            }
            String zipFileName = RuoYiConfig.getDownloadPath() + fileName;
            String sourceFolder = packPath;// 需要压缩的文件夹
            zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
            // 压缩文件夹
            compressFolder(sourceFolder, folderName, zipOutputStream);
            System.out.println("Folder compressed successfully!");
            SysUpload sysUpload = new SysUpload();
            sysUpload.setFileName(fileName);
            sysUpload.setModuleName("离线部署_" + bDeviceZt.getDeviceMac());
            sysUpload.setUpdateBy(SecurityUtils.getUsername());
            sysUpload.setUpdateTime(new Date());
            sysUpload.setResourceUrl("/profile/download/" + fileName);
            sysUpload.setModuleGuid(bDeviceZt.getGuid());
            sysUploadService.insertSysUpload(sysUpload);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
                fileOutputStream.flush();
                zipOutputStream.closeEntry();
                zipOutputStream.close();
                zipOutputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "/profile/download/" + fileName;
    }
}
